package com.xbh.management.security;

import com.alibaba.fastjson.JSON;
import com.nimbusds.jose.JOSEException;
import com.xbh.common.utils.RedisUtils;
import com.xbh.common.web.core.Result;
import com.xbh.management.entity.PayloadDTO;
import com.xbh.management.entity.SecurityUserVO;
import com.xbh.management.model.ManLoginLog;
import com.xbh.management.service.ManLoginLogService;
import com.xbh.management.utils.JwtUtilManagement;
import com.xbh.management.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @program: management-center
 * @description: 自定义登录验证成功处理器
 * @author: 许宝华
 * @create: 2021-10-08 09:03
 */
@Slf4j
public class LoginSuccessHandler implements AuthenticationSuccessHandler {


    private JwtUtilManagement jwtUtilManagement;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private ManLoginLogService manLoginLogService;

    private static String signatureAlgorithmSecret="abcdefghijklmnopqrstuvwxyz123456789";

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //认证成功，得到认证成功之后的用户信息
        log.info("自定义登录处理器认证成功");
        log.info("当前的登录时间为：" + new Date().toString());
        log.info("当前的登录IP为：" + request.getRemoteAddr());

        SecurityUserVO user = (SecurityUserVO) authentication.getPrincipal();
        //根据用户名生成token
        PayloadDTO payload = jwtUtilManagement.getPayload(user.getCurrentUserInfo());
        // 生成token
        String payloadJsonString = JSON.toJSONString(payload);
        String token;
        try {
            token = JwtUtilManagement.generateToken(payloadJsonString, signatureAlgorithmSecret);
            //将用户权限列表和token存放到Redis中,并设置token过期时间
            redisUtils.set("token_"+user.getCurrentUserInfo().getUsername(),token,3*1L, TimeUnit.HOURS);
            redisUtils.set(user.getCurrentUserInfo().getUsername(),user.getPermissionValueList());
            //返回token
            Map<String,Object> userInfoAndToken=new HashMap<>();
            userInfoAndToken.put("userInfo",user.getCurrentUserInfo());
            userInfoAndToken.put("token",token);
            userInfoAndToken.put("menu",user.getPermissionValueList());
            //登录日志
            ManLoginLog manLoginLog = new ManLoginLog();
            manLoginLog.setUsername(user.getCurrentUserInfo().getUsername());
            manLoginLog.setUserId(user.getCurrentUserInfo().getUserId());
            manLoginLog.setLogInfo("登陆成功");
            manLoginLog.setLogTitle("登录信息");
            manLoginLog.setNodeColor("green");
            manLoginLog.setCreatePerson(user.getCurrentUserInfo().getUsername());
            manLoginLog.setUpdatePerson(user.getCurrentUserInfo().getUsername());
            manLoginLogService.save(manLoginLog);
            ResponseUtil.out(response, Result.result("000","登陆成功",userInfoAndToken));
        } catch (JOSEException e) {
            e.printStackTrace();
        }
    }
}
